package org.feng.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

/**
 * @Author feng
 * @Date 2022/6/14 11:30
 * @Description TODO
 */
@Component
public class SwaggerFilter extends AbstractGatewayFilterFactory {

    @Override
    public GatewayFilter apply(Object config) {


        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String path = request.getURI().getPath();
            if (path.contains("/v2/api-docs")) {
                String[] split = path.split("/");
                StringBuilder url = new StringBuilder("/");
                for (int i = 2; i < split.length; i++) {
                    if (i == split.length - 1) {
                        url.append(split[i]);
                    } else {
                        url.append(split[i]).append("/");
                    }
                }
                ServerHttpRequest newRequest = request.mutate().path(url.toString()).build();
                exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
                return chain.filter(exchange.mutate().request(newRequest).build());
            } else {
                return chain.filter(exchange);
            }
        };
    }
}
